﻿using Dapper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ExcelFileQueryTool
{
    public partial class frmSalesDetail : Form
    {
        private const string FORM_TITLE = "客户数据维护[DB]";

        private static Dictionary<string, short> SalesType = new Dictionary<string, short> 
            {
                {"未定义",(short)BillSalesType.NotDefined},
                {"销售",(short)BillSalesType.Sale},
                {"进货",(short)BillSalesType.Purchase},
                {"收入",(short)BillSalesType.Income},
                {"支出",(short)BillSalesType.Pay},
                {"退货",(short)BillSalesType.ReturnForSale},
                {"优惠",(short)BillSalesType.Discount},
                {"损失",(short)BillSalesType.Lost}
            };

        private BillSalesService _salesService = new BillSalesService(AppConfig.DBConnectionString);
        private CrmPeopleService _peopleService = new CrmPeopleService(AppConfig.DBConnectionString);

        private int _previousSalesId = 0;
        private bool _onEditMode = false;

        public frmSalesDetail()
        {
            InitializeComponent();

            this.Text = FORM_TITLE + "[+]";

            cboxBillType.DisplayMember = "Key";
            cboxBillType.ValueMember = "Value";
            cboxBillType.DataSource = new BindingSource { DataSource = SalesType };
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveData();

            if (txtExcelData.Lines != null && txtExcelData.Lines.Length > 0)
            {
                var lines = txtExcelData.Lines;
                txtExcelData.Clear();

                for (int i = 1; i < lines.Length; i++)
                {
                    txtExcelData.AppendText(lines[i]);
                    if (i < lines.Length - 1)
                        txtExcelData.AppendText(Environment.NewLine);
                }
            }

            //MessageBox.Show("保存成功！");
            MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户销售记录详情",
                                Content = "保存成功！"
                            });
        }

        private BillSales GetData()
        {
            var data = new BillSales();

            if (_onEditMode)
                data.Id = _previousSalesId;

            data.ClientId = int.Parse(lblClientIdValue.Text);
            data.ClientName = txtName.Text.Trim();
            data.SalesDate = dpSalesDate.Value.Date;
            data.ProductName = txtProduct.Text.Trim();
            data.ProductAmount = numAmount.Value;
            data.ProductUnit = txtUnit.Text.Trim();
            data.ProductPrice = numPrice.Value;
            data.LoadingFee = numLoadingFee.Value;
            data.ShippingFee = numShippingFee.Value;
            data.Note = txtNote.Text.Trim();
            data.BillNumber = txtBillNO.Text.Trim();
            data.TotalMoney = data.ProductAmount * data.ProductPrice + data.LoadingFee + data.ShippingFee;
            data.CreatedTime = DateTime.Now;
            data.LastUpdatedTime = DateTime.Now;
            data.ProductId = 0;
            data.ShippingAddress = txtAdress.Text.Trim();
            data.ShippingMethod = data.Note;
            data.Status = (short)DBRecordStatus.Normal;
            data.BillType = (short)cboxBillType.SelectedValue;

            return data;
        }

        private void SetData(BillSales data)
        {
            _previousSalesId = data.Id.Value;
            lblClientIdValue.Text = data.ClientId.ToString();
            txtName.Text = data.ClientName;
            dpSalesDate.Value = data.SalesDate;
            txtProduct.Text = data.ProductName;
            numAmount.Value = data.ProductAmount;
            txtUnit.Text = data.ProductUnit;
            numPrice.Value = data.ProductPrice;
            numLoadingFee.Value = data.LoadingFee;
            numShippingFee.Value = data.ShippingFee;
            txtNote.Text = data.Note;
            txtBillNO.Text = data.BillNumber;
            txtAdress.Text = data.ShippingAddress;
            cboxBillType.SelectedValue = data.BillType;
        }

        private void SaveData()
        {
            var data = GetData();

            if (_onEditMode)
            {
                data.LastUpdatedTime = DateTime.Now;
                _salesService.Update(data);
            }
            else
            {
                _previousSalesId = _salesService.Add(data);
            }

            _onEditMode = false;
            this.Text = FORM_TITLE + "[+]";
        }

        private void txtProduct_TextChanged(object sender, EventArgs e)
        {
            // just a possible value,there is a chance for end-user to manully change it
            cboxBillType.SelectedValue = ClientFileService.GetBillTypeByProduct(txtProduct.Text.Trim());
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            var name = txtName.Text.Trim();
            if (name == string.Empty)
                return;

            var people = _peopleService.GetByName(name);
            if (people == null)
            {
                lblClientIdValue.Text = "0";
            }
            else
            {
                lblClientIdValue.Text = people.Id.ToString();
            }
        }

        private void btnLoadPrevious_Click(object sender, EventArgs e)
        {
            if (_previousSalesId > 0)
            {
                var data = _salesService.GetById(_previousSalesId);

                if (data != null)
                {
                    SetData(data);
                    _onEditMode = true;
                    this.Text = FORM_TITLE + "[*]";
                }
            }
        }

        private void numAmount_Enter(object sender, EventArgs e)
        {
            numAmount.Select(0, numAmount.ToString().Length);
        }

        private void numPrice_Enter(object sender, EventArgs e)
        {
            numPrice.Select(0, numPrice.ToString().Length);
        }

        private void numLoadingFee_Enter(object sender, EventArgs e)
        {
            numLoadingFee.Select(0, numLoadingFee.ToString().Length);
        }

        private void numShippingFee_Enter(object sender, EventArgs e)
        {
            numShippingFee.Select(0, numShippingFee.ToString().Length);
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            var name = txtName.Text.Trim();
            if (string.IsNullOrEmpty(name))
                return;

            var files = Directory.GetFiles(AppConfig.SourceFolder, AppConfig.FilePattern, SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
                return;

            var f = files[0];
            if (File.Exists(f) == false)
            {
                //MessageBox.Show("客户文件不存在！", "提示", MessageBoxButtons.OK);
                MessageDispatcherManager.DispatchMessage(
                            new AppMessage
                            {
                                Time = DateTime.Now,
                                Level = AppMessageLevel.Info,
                                Title = "客户销售记录详情",
                                Content = "客户文件不存在！"
                            });
                return;
            }

            using (Process.Start(f)) { }
        }
    }
}
